<?php
namespace jy_teamshop;
defined('BY_JYA') or exit('error');
/*
	分销佣金
	分销插件所有金额字段均保存整形，精确到分。显示时，除以100然后保留两位小数即可
	佣金比例字段保存整形，值为万分数，相当于百分数的精确到小数点后2位。即展示到前端时，需要除以100，换算成百分数显示
*/
class member extends \plugin{
	public function checklogin($isuid=false){
		global $_AR;
		if(!$_SESSION['uid']){
			if(!$isuid){
				$_SESSION['forward_url']=$_AR['access_json'];
				model('core/core')->checklogin();
			}
		}else{
			$member=pdo_get('core_members',array('id'=>$_SESSION['uid'],'uniacid'=>$_SESSION['uniacid']),array('id'));
			if(empty($member)){
				model('core/member')->logout();
				model('core/core')->checklogin('jy_teamshop/myhome/');
			}else{
				$user=pdo_get('jy_teamshop_member',array('mid'=>$_SESSION['uid'],'uniacid'=>$_SESSION['uniacid']),array('id'));
				if(!$user['id']){
					$insert=array(
						'mid'=>$_SESSION['uid'],
						'uniacid'=>$_SESSION['uniacid'],
						'agent_id'=>$member['fromuser']?:$_SESSION['fromuser'],
						'createtime'=>TIMESTAMP,
					);
					pdo_insert('jy_teamshop_member',$insert);
				}
			}
			if(!$member['is_agent']){
				$this->set_agent($_SESSION['uid']);
			}
		}
	}
	/*
		核实分销商,$isset无条件成为分销商
	*/
	public function checkmember($mid=0,$isexi=false,$isset=false){
			$mid=$mid?:$_SESSION['uid'];
			$member=$this->get('member',array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));			
			$page_setting=$this->plugin_setting('page_setting');
			$page_setting['tagent']=$page_setting['tagent']?:'代理商';
			if(!$member['mid']){
				$this->checklogin($mid);
				$member=$this->get('member',array('mid'=>$mid));
			}
			if(!$member['is_agent']){
				//如果成为分销商无条件，此处自动申请成为分销商
				if($this->setting['become']==0 || $isset || $this->session('becomefromuser')){
					//分销商无需审核，此处自动审核
					$ispass=true;
					$this->apply_agent($member['mid']);
					if($this->setting['become_check'] && $isexi){
						exi('申请正在审核请耐心等待！','error','jy_teamshop/agent.apply/');
					}elseif($isset){
						return true;
					}
				}elseif($this->setting['become']==2){
					//消费次数
					$buynums=pdo_count('jy_weishop_order',array('ispay'=>1,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']),'id');
					if($buynums>=$this->setting['num']){
						$ispass=true;
						$this->apply_agent($member['mid']);
						if($this->setting['become_check'] && $isexi){
							exi('申请正在审核请耐心等待。','error','jy_teamshop/agent.apply/');
						}
					}elseif($isexi){
						exi('你还不是'.$page_setting['tagent'].'，请前往申请！','error','jy_teamshop/agent.apply/');
					}
				}elseif($this->setting['become']==3){
					//消费金额
					$buyfee=pdo_getsum('jy_weishop_order',array('ispay'=>1,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']),'price');
					if($buyfee>=$this->setting['money']){
						$ispass=true;
						$this->apply_agent($member['mid']);
						if($this->setting['become_check'] && $isexi){
							exi('申请正在审核请耐心等待。','error','jy_teamshop/agent.apply/');
						}
					}elseif($isexi){
						exi('你还不是'.$page_setting['tagent'].'，请前往申请！','error','jy_teamshop/agent.apply/');
					}
				}elseif($this->setting['become']==4){
					//购买指定商品
					$become_goods=$this->setting['become_goods'];
					foreach($become_goods as &$bgv){
						$isbuy=pdo_count('jy_weishop_order_goods',array('mid'=>$member['mid'],'goodsid'=>$bgv['id'],'ispay'=>1),'id');
						if($isbuy>0){
							$ispass=true;
							$this->apply_agent($member['mid']);
							break;
						}
					}
					if($this->setting['become_check'] && $isexi && $ispass){
						exi('您的申请，正在审核请耐心等待！','error','jy_teamshop/apply/');
					}elseif($isexi && !$ispass){
						exi('你还不是'.$page_setting['tagent'].'，请前往申请！','error','jy_teamshop/agent.apply/');
					}
				}else{
					if($isexi){
						exi('你还不是'.$page_setting['tagent'].'，请前往申请！','error','jy_teamshop/agent.apply/');
					}
				}
				if($ispass){
					exi('','','jy_teamshop/agent.index/');
				}
			}elseif($member['stop'] && $isexi){
				if($isset){
					return true;
				}
				exi('你的'.$page_setting['tagent'].'身份已禁用！','error','jy_teamshop/agent.apply/');
			}elseif((!$member['realname'] || !$member['mobile']) && $isexi){
				if($isset){
					return true;
				}
				if($this->setting['become_reg']==1){
					exi('请先完善信息','error','jy_teamshop/agent.info/');
				}else{
					
				}
			}
			return $member;
	}
	/*
		设置上下级关系
	*/
	public function set_parent($mid,$parent_id,$ischange=false){
		$member=$this->get('member',array('mid'=>$mid),array('level_id','agent_id'));
		$old_agent_id=$member['agent_id'];
		$isuser=pdo_getcolumn('core_members',array('id'=>$parent_id),'id');
		//如果不存在该会员，或已经有上级了，取消执行。
		if(($old_agent_id || !$isuser) && !$ischange){
			return true;
		}
		//如果他的上级是我
		$ta_agent_id=$this->getcolumn('member',array('mid'=>$parent_id),'agent_id');
		if($ta_agent_id==$mid){
			return true;
		}
		//如果上级是自己，上级ID归零
		if($mid==$parent_id){
			return true;
		}
		$this->update('member',array('agent_id'=>$parent_id),array('mid'=>$mid));
		//上级获得抽奖机会
		$gamepost=array(
			'type'=>8,
			'level_id'=>$member['level_id'],
		);
		model('jy_weishop/game')->up_addgame($gamepost,$parent_id);
		if(9>0){
			$agent_id=$old_agent_id;
			for($i=0;$i<9;$i++){
				if(!$agent_id){
					break;
				}
				$agent_id=$this->getcolumn('member',array('mid'=>$agent_id),'agent_id');
			}
			$agent_id=$parent_id;
			for($i=0;$i<9;$i++){
				if(!$agent_id){
					break;
				}
				//只有一级才增加一级下级
				if($i==0){
					$member_update=array(
						'member_num +='=>1,
						'agent_num +='=>1,
						'member_num_next +='=>1,
						'agent_num_next +='=>1,
					);
				}else{
					$member_update=array(
						'member_num +='=>1,
						'agent_num +='=>1,
					);
				}
				$this->update('member',$member_update,array('mid'=>$agent_id));
				$this->update_agent_level($agent_id);
				$this->model('notice')->notice_fenxiao_xiajiadd($mid,$agent_id);
				$agent_id=$this->getcolumn('member',array('mid'=>$agent_id),'agent_id');
			}
		}
		return true;
	}
	/*
		申请成为分销商
	*/
	public function apply_agent($mid,$noapply=false){
		$apply=$this->get('apply',array('mid'=>$mid));
		if($apply && $apply['status']!=2){
			if($apply['status']==1){
				$member_update=array(
					'is_agent'=>1,
					'agenttime'=>TIMESTAMP,
				);
				$this->update('member',$member_update,array('mid'=>$apply['mid']));
				$this->model('notice')->notice_fenxiao_add($mid);
			}
			return;
		}
		if($apply['status']!=2){
			$new_apply=array(
				'uniacid'=>$_SESSION['uniacid'],
				'mid'=>$mid,
				'status'=>0,
				'createtime'=>TIMESTAMP,
			);
			$this->insert('apply',$new_apply);
			$apply_id=$this->insertid();
		}else{
			$this->update('apply',array('status'=>0),array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
			$apply_id=$apply['id'];
		}
		if(!$this->setting['become_check']){
			//分销商无需审核，此处自动审核
			$this->check_apply($apply_id,1);
		}
		return true;
	}
	/*
		审核分销商
	*/
	public function check_apply($apply_id,$status,$remark=''){
		if(!$apply_id || !$status){
			return;
		}
		$apply=$this->get('apply',array('id'=>$apply_id));
		if(!$apply){
			return;
		}
		$update=array(
			'status'=>$status,
			'complete_time'=>TIMESTAMP,
		);
		if($update['status']==1){
			//审核通过，修改会员状态，修改上线相关数据
			$member_update=array(
				'is_agent'=>1,
				'agenttime'=>TIMESTAMP,
			);
			$this->update('member',$member_update,array('mid'=>$apply['mid']));
			pdo_update('jy_weishop_member',array('level'=>1),array('mid'=>$apply['mid']));
			//审核通过，此处增加上线的相关数据
			$agent_id=$this->getcolumn('member',array('mid'=>$apply['mid']),'agent_id');
			for($i=0;$i<9;$i++){
				if(!$agent_id){
					break;
				}
				$agent_update=array('agent_num +='=>1);
				if($i==0){
					$agent_update['agent_num_next +=']=1;
				}
				$this->update('member',$agent_update,array('mid'=>$agent_id));
				$this->update_agent_level($agent_id);
				$agent_id=$this->getcolumn('member',array('mid'=>$agent_id),'agent_id');
			}
		}else{
			$update['remark']=$remark;
		}
		$this->update('apply',$update,array('id'=>$apply_id));
		return true;
	}
	/*
		成为万家会员
	*/
	public function set_agent($mid=0){
		$mid=$mid?:$_SESSION['uid'];
		$member=$this->get('member',array('mid'=>$mid));
		if($member['is_agent']){
			return false;
		}
		if(!$this->setting['become']){
			$can=true;
		}elseif($this->setting['become']==2){
			$num=pdo_count('jy_weishop_order',array('mid'=>$mid,'ispay'=>1));
			if($num>=$this->setting['num']){
				$can=true;
			}
		}elseif($this->setting['become']==3){
			$money=pdo_getsum('jy_weishop_order',array('mid'=>$mid,'ispay'=>1),'price');
			if($money>=$this->setting['money']){
				$can=true;
			}
		}elseif($this->setting['become']==4){
			$become_goods=$this->setting['become_goods'];
			foreach($become_goods as &$bgv){
					$isbuy=pdo_count('jy_weishop_order_goods',array('mid'=>$mid,'goodsid'=>$bgv['id'],'ispay'=>1),'id');
					if($isbuy>0){
						$can=true;
						continue;
					}
			}
		}
		if($can){
			$member_update=array(
				'is_agent'=>1,
				'agenttime'=>TIMESTAMP,
			);
			$this->update('member',$member_update,array('mid'=>$mid));
			$this->model('notice')->notice_fenxiao_add($mid);
		}
		return true;
	}
	/*
		禁用分销商
	*/
	public function stop_agent($agent_id){
		$this->update('member',array('stop'=>1),array('mid'=>$agent_id));
	}
	/*
		恢复分销商
	*/
	public function start_agent($agent_id){
		$this->update('member',array('stop'=>0),array('mid'=>$agent_id));
	}
	/*
		获取会员的各项参数
		
		问题：开启分销内购时
			推广订单如何算？
			下线如何算？
			
			计算下线时，分销级数在设置的级数基础上-1，其他不变
			计算推广订单时，在上面的基础上+自己的订单
	*/
	public function get_member($mid){
		$res=array();
		//获取一级下线数量
		$members=$this->getall('member',array('uniacid'=>$_SESSION['uniacid'],'agent_id'=>$mid),array('mid','is_agent'),'mid');		
		if(!$members){
			$res=array(
				'member_num'=>'0',
				'agent_num'=>'0',
				'order_price'=>'0',
				'order_num'=>'0',
				'myorder_price'=>'0',
				'order_price_next'=>'0',
				'order_num_next'=>'0',
				'member_num_next'=>'0',
				'agent_num_next'=>'0',
			);
			return $res;
		}
		//获取直属下级分销商数量
		$res['agent_num_next']=$this->count('member',array('uniacid'=>$_SESSION['uniacid'],'is_agent'=>1,'agent_id'=>$mid));
		$res['member_num_next']=count($members);
		$member_ids=array_keys($members);
		$res['order_num_next']=$this->count('order',array('mid'=>$member_ids));
		$res['order_price_next']=$this->sum('order',array('mid'=>$member_ids),'order_price');
		//获取下线总数，向下遍历系统设置的指定分销层数
		$commission_level=9;
		if($this->setting['self_commission']){
			//开启分销内购
			$commission_level=$commission_level-1;
		}
		if($commission_level>1){
			$next_ids=$member_ids;
			for($i=1;$i<$commission_level;$i++){
				$next_members=$this->getall('member',array('uniacid'=>$_SESSION['uniacid'],'agent_id'=>$next_ids),array('mid','is_agent'),'mid');
				if(!$next_members){
					break;
				}
				$members=array_merge($next_members,$members);
				$next_ids=array_keys($next_members);
				$member_ids=array_merge($next_ids,$member_ids);
			}
		}
		$res['member_num']=count($member_ids);
		$res['order_num']=$this->count('order',array('mid'=>$member_ids));
		$res['order_price']=$this->sum('order',array('mid'=>$member_ids),'order_price');
		$res['myorder_price']=$this->sum('order',array('mid'=>$mid),'myorder_price');
		$res['agent_num']=0;
		foreach($members as $member){
			if($member['is_agent']){
				$res['agent_num']++;
			}
		}
		if($this->setting['self_commission']){
			//开启分销内购，此处加上用户自己的订单作为推广订单的一部分
			$self_order_num=$this->count('order',array('mid'=>$mid));
			$self_order_money=$this->sum('order',array('mid'=>$mid),'order_price');
			$res['order_num_next']=$self_order_num;
			$res['order_price_next']=$self_order_money;
			$res['order_num']+=$self_order_num;
			$res['order_price']+=$self_order_money;
		}
		return $res;
	}
	/*
		升级分销商等级
		先检测会员身份是否为正常分销商
		然后获取分销商当前等级的下一等级升级条件
		然后逐个条件对比，看是否满足升级条件
		如果全部满足，则升级到相应等级
		
		何时触发升级分销商等级检测呢？
		
	*/
	public function update_agent_level($mid,$orderid=0){
		$member=$this->get('member',array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
		if($member['stop'] || !$member['is_agent']){
			if(!$member['is_agent']){
				$this->set_agent($mid);
			}
			return;
		}
		$level=pdo_get('jy_weishop_member_level',array('id'=>$member['level_id'],'uniacid'=>$_SESSION['uniacid']));
		$parameter=array(
			'params'=>array('uniacid'=>$_SESSION['uniacid'],'level >'=>$level['level']),
			'orderby'=>'level desc',
		);
		$levels=pdo_getall('jy_weishop_member_level',$parameter['params'],'','',$parameter['orderby']);
		if(empty($levels)){
			return;
		}
		$level_up_types=$this->model('model')->current_level_up_types();//获取当前设置的分销商等级升级条件
		if(!$level_up_types){
			return;
		}
		$members=$this->getall('member',array('uniacid'=>$_SESSION['uniacid'],'agent_id'=>$newteammids),array('mid'),'mid');
		if($members){
			$mids=array_keys($members);
		}
		$mids[]=$mid;
		foreach($levels as $lv){
			$conditions=json_decode($lv['conditions'],true);
			if(!$level_up_types || !$lv['id']){
				continue;
			}
			$up=false;
			foreach($level_up_types as $type){
				if(!$this->level_up_types[$type]){
					continue;
				}
				if($type=='order_price'){
					$order_price=pdo_getsum('jy_weishop_order',array('ispay'=>1,'mid'=>$mids,'uniacid'=>$_SESSION['uniacid']),'price');
					if($order_price>=$conditions[$type] && $conditions[$type]){
						$up=true;
						break;
					}
				}
				if($type=='order_num'){
					$order_num=pdo_count('jy_weishop_order',array('ispay'=>1,'mid'=>$mids,'uniacid'=>$_SESSION['uniacid']));
					if($order_num>=$conditions[$type] && $conditions[$type]){
						$up=true;
						break;
					}
				}
				//直接推荐掌柜人数
				if($type=='agent_num_next'){
					$agent_num_next=$this->count('member',array('level_id >'=>0,'agent_id'=>$mid,'uniacid'=>$_SESSION['uniacid']),'mid');
					if($agent_num_next>=$conditions[$type] && $conditions[$type]){
						$up=true;
						break;
					}
				}
				if($type=='myorder_price'){
					$myorder_price=pdo_getsum('jy_weishop_order',array('ispay'=>1,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']),'price');
					if($myorder_price>=$conditions[$type] && $conditions[$type]){
						$up=true;
						break;
					}
				}
				if($type=='myorder_num'){
					$myorder_num=pdo_count('jy_weishop_order',array('ispay'=>1,'mid'=>$mid,'uniacid'=>$_SESSION['uniacid']),'id');
					if($myorder_num>=$conditions[$type] && $conditions[$type]){
						$up=true;
						break;
					}
				}
				if($type=='buy_goods' && $next_level['goods_ids'] && $orderid){
					$goods_ids=json_decode($next_level['goods_ids'],true);
					$isbuy=false;
					foreach($goods_ids as $gv){
							$isbuynum=pdo_getsum('jy_weishop_order_goods',array('ispay'=>1,'mid'=>$mid,'goodsid'=>$gv['id'],'uniacid'=>$_SESSION['uniacid']),'id');
							if($isbuynum){
								$isbuy=true;
							}
					}
					if(!$isbuynum && $member['level_id']){
						$goods_ids=json_decode($level['goods_ids'],true);
						$isbuy=false;
						foreach($goods_ids as $gv){
								$isbuynum=pdo_getsum('jy_weishop_order_goods',array('ispay'=>1,'mid'=>$mid,'goodsid'=>$gv['id'],'uniacid'=>$_SESSION['uniacid']),'id');
								if($isbuynum){
									$isbuy=true;
								}
						}
					}
					if($isbuy){
						$up=true;
						break;
					}
				}
			}
			if($up){
				$next_level=$lv;
				break;
			}
		}
		if($up){
			$update=array(
				'level_id'=>$next_level['id'],
			);
			if($next_level['feetype'] && $next_level['creditfee']){
				model('core/member')->member_credit($mid,'credit'.$next_level['feetype'],$next_level['creditfee'],true,'jy_teamshop','达到指定分销等级获得奖励');
			}
			$this->update('member',$update,array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
			pdo_update('jy_weishop_member',array('level'=>$next_level['id']),array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
		}
		if($isbuynum){
				if($this->setting['is_leveltime'] && $this->setting['leveltime']){
						$num=$isbuynum?:1;
						$member['t_time']+$num*$this->setting['leveltime']*24*3600;
						$nowtime=$up || $member['t_time']<TIMESTAMP?TIMESTAMP:$member['t_time'];
						$update=array(
								't_time'=>$nowtime+$num*$this->setting['leveltime']*24*3600
						);
						$this->update('member',$update,array('mid'=>$mid));
				}
		}
		return true;
	}
	public function min_agent_level($mid=0){
		//
		$mid=$mid?:$_SESSION['uid'];
		$member=$this->get('member',array('mid'=>$mid));
		//开启有效期后，降级
		if($this->setting['is_leveltime'] && $this->setting['leveltime']){
			if($member['t_time'] && $member['t_time']<TIMESTAMP){
				$level=pdo_get('jy_weishop_member_level',array('id'=>$member['level_id']));
				$this->update('member',array('level_id'=>$level['t_level_id'],'t_time'=>0),array('mid'=>$mid));
			}
		}
	}
	/*
		核实指定等级活动
	*/
	public function upgametime($mid_ids=array(),$mid=0){
		$mid=$mid?:$_SESSION['uid'];
		if(count($mid_ids)){
			foreach($mid_ids as $mv){
				$level_id=$this->getcolumn('member',array('mid'=>$mv),'level_id');
				$gamepost=array(
					'type'=>8,
					'level_id'=>$level_id
				);
				//model('jy_weishop/game')->up_addgame($gamepost,$mid);
			}
		}
	}
	public function setfromuser($mid=0){
		$mid=$mid?:$_SESSION['uid'];
		$fromuser=pdo_getcolumn('jy_teamshop_member',array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']),'agent_id');
		if(!$fromuser && $_SESSION['fromuser'] && $_SESSION['fromuser'] !=$mid){
			pdo_update('jy_teamshop_member',array('agent_id'=>$_SESSION['fromuser']),array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
		}
		return false;
	}
	public function getdetail($mid=0){
		$mid=$mid?:$_SESSION['uid'];
		$user=pdo_get('jy_teamshop_member',array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
		return $user;
	}
	//type 0充值，1消费，2冻结，3解冻，4冻结消费，5退款，6提现,7返现
	public function recharge($mid=0,$fee=0,$type=0,$remark=''){
		$mid=$mid?:$_SESSION['uid'];
		if(!intval($fee)){
			return false;
		}
		$logtype=5;
		$member=pdo_get('jy_teamshop_member',array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
		$update=array();
		if($type==0){
			$update['baofee +=']=$fee;
			$msg='充值:￥'.$fee;
		}elseif($type==1){
			$update['baofee -=']=$fee;
			$msg='消费:￥'.$fee;
		}elseif($type==2){
			$update['baofee -=']=$fee;
			$update['freeze +=']=$fee;
			$msg='冻结:￥'.$fee;
		}elseif($type==3){
			$update['baofee +=']=$fee;
			$msg='解冻:￥'.$fee;
			if($member['freeze']<$fee){
				$update['freeze']=0;
			}else{
				$update['freeze -=']=$fee;
			}
		}elseif($type==4){
			$msg='参与消费解冻:￥'.$fee;
			if($member['freeze']<$fee){
				$update['freeze']=0;
			}else{
				$update['freeze -=']=$fee;
			}
		}elseif($type==5){
			$update['baofee +=']=$fee;
			$msg='退款:￥'.$fee;
		}elseif($type==6){
			$update['baofee -=']=$fee;
			$msg='提现到余额:￥'.$fee;
		}elseif($type==7){
			$update['baofee +=']=$fee;
			$msg='参与返现:￥'.$fee;
			$logtype=7;
		}
		$user=pdo_update('jy_teamshop_member',$update,array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
		$params=array(
			'msg'=>$msg,
			'status'=>1,
			'mid'=>$mid,
		);
		$this->model('model')->set_log($params,$logtype);
		return true;
	}
	public function getprice($member,$goods_id=0,$optionid=0){
		$goods=$this->get('goods',array('goods_id'=>$goods_id));
		$getprice=array();
		if(!$goods['ignore'] && $goods['id']){
			$goods['diyprice']=$goods['diyprice']?json_decode($goods['diyprice'],true):array();
			if($goods['diyprice']){
				foreach($goods['diyprice'] as $dv){
					if($member['level_id']==$dv['level_id'] && $member['ishehuo']==$dv['ishehuo']){
						if($optionid){
							$getprice['price']=$dv['oprice'.$optionid];
						}else{
							$getprice['price']=$dv['price'];
						}
						$getprice['isprice']=1;
						break;
					}
				}
			}
		}
		return $getprice;
	}
}